//
//  ShenPiXiangQingViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/22.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "ShenPiXiangQingViewController.h"
#import "ShenPiLiuChengRenYuanTableViewCell.h"
#import "AlertRemindView.h"
#import "ShenPiXiangQingTableViewCell.h"
#import "ShenPiXiangQingFuJianTableViewCell.h"
#import "ShenPiXiangQingGuanLianKeHuTableViewCell.h"
#import "ShenPiJuJueView.h"
#import "LiaoTianWenJianChaKanViewController.h"
#import "XLPhotoBrowser.h"
#import "ZBNetworking.h"
#import "KeHuXiangQingViewController.h"

#import "YuYinBoFangView.h"
#import "ChaKanQuanBuViewController.h"
#import "ShenPiXiangQingBiaoTouTableViewCell.h"
#import "ShenPiXiangQingShenPiNeiRongTableViewCell.h"

#import "ShenPiXiangQingShenPiJiLuHeaderView.h"

@interface ShenPiXiangQingViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UIDocumentPickerDelegate>{
    NSArray *examineFlowList;
    NSMutableDictionary *dataInfoDictionary;
    YuYinBoFangView *yuYinView;
    NSArray *keXuanXiangArray;
    NSArray *liShiShenPiArray;
}
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeight;

@end

@implementation ShenPiXiangQingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.customNavBar.title = @"详情";
    
    _topSpace.constant = NavaBarHeight;
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiLiuChengRenYuanTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiLiuChengRenYuanTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiXiangQingTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiXiangQingTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiXiangQingFuJianTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiXiangQingFuJianTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiXiangQingGuanLianKeHuTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiXiangQingGuanLianKeHuTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiXiangQingBiaoTouTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiXiangQingBiaoTouTableViewCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiXiangQingShenPiNeiRongTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiXiangQingShenPiNeiRongTableViewCell"];
    
    
    
    
    [self yziDingYiZiDuanChaXun];
    if(_recordId.length > 0){
        
        [self huoQuLiShiShenPiLiuCheng];
        
//        [self huoQuShenPiJiLu];
    }

    yuYinView = [YuYinBoFangView view];
    [[AppDelegate shareInstance].window addSubview:yuYinView];
  
    yuYinView.frame = CGRectMake(0, ScreenHeight-107-30, ScreenWidth, 107);
    yuYinView.hidden = YES;
    

}

- (void)viewWillDisappear:(BOOL)animated{
    yuYinView.hidden = YES;
    [yuYinView closeVoice];
}
//自定义字段查询
- (void)yziDingYiZiDuanChaXun{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"1" forKey:@"isDetail"];
    [paraDic setValue:@"1" forKey:@"type"];
    [paraDic setValue:_examineId forKey:@"examineId"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/oaExamine/getField" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            keXuanXiangArray = [info objectForKey:@"data"];
        }
        
        [self huoQuShenPiXiangQing];
    }];
}

//    获取详情
- (void)huoQuShenPiXiangQing{
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:[NSString stringWithFormat:@"/oaExamine/queryOaExamineInfo/%@",_examineId] andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            dataInfoDictionary = [NSMutableDictionary dictionaryWithDictionary:[info objectForKey:@"data"]];
            [_mainTableView reloadData];
            
            if(_recordId.length == 0){
                _recordId = GetHandleString(dataInfoDictionary, @"examineRecordId");
                if(_recordId.length > 0){
                    [self huoQuShenPiJiLu];
                }
            }
        }
    }];
}

//获取历史审批流程
- (void)huoQuLiShiShenPiLiuCheng{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:_recordId forKey:@"recordId"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/examineRecord/queryExamineRecordLog" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            liShiShenPiArray = [info objectForKey:@"data"];
        }
        
        [self huoQuShenPiJiLu];
    }];
}
//获取审批记录
- (void)huoQuShenPiJiLu{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:_recordId forKey:@"recordId"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/examineRecord/queryExamineRecordList" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            examineFlowList = [[info objectForKey:@"data"] objectForKey:@"examineFlowList"];
            
            
            NSDictionary *tempDic= [NSDictionary dictionary];
            for (NSDictionary *dataDic in examineFlowList) {
                for (NSDictionary * userListDic in [dataDic objectForKey:@"userList"]) {
                    NSLog(@"=======%@,=======%@",GetHandleString(userListDic, @"userId"),userInfoId);
                    if([GetHandleString(userListDic, @"userId") isEqualToString:GetHandleString(USERINFO, @"userId")]){
                        tempDic = userListDic;
                        break;
                    }
                }
            }
            
            if([GetHandleString(tempDic, @"examineStatus") integerValue] == 3){
                _bottomViewHeight.constant = 66 + ScreenBottom;
                _bottomView.hidden = NO;
            }else{
                _bottomViewHeight.constant = 0;
                _bottomView.hidden = YES;
            }
            
            
            [_mainTableView reloadData];
        }
    }];
}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5+examineFlowList.count;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0 || section == 2 || section == 4){
        return 1;
    }
    if(section == 1){
        return keXuanXiangArray.count;
    }
    if(section == 3){
        if([[dataInfoDictionary objectForKey:@"file"] isKindOfClass:[NSArray class]]){
//            return [[dataInfoDictionary objectForKey:@"file"] count];
            return 1;
        }
        return 0;
    }
    NSArray *userList = [examineFlowList[section-5] objectForKey:@"userList"];
    return userList.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section > 4){
        ShenPiXiangQingShenPiJiLuHeaderView *header = [ShenPiXiangQingShenPiJiLuHeaderView view];
        NSDictionary *dataDic = examineFlowList[section-5];
        if(section == 5){
            if([GetHandleString(dataDic, @"name") length] > 0){
                header.nameLabel.text = GetHandleString(dataDic, @"name");
            }else{
                header.nameLabel.text = @"发起人";
            }
            header.timeLabel.text = @"发起审批";
            header.topLineImage.hidden = YES;
        }else{
            header.topLineImage.hidden = NO;
            header.nameLabel.text = GetHandleString(dataDic, @"name");
            if([GetHandleString(dataDic, @"type") intValue] == 1){
                header.timeLabel.text = [NSString stringWithFormat:@"%ld人依次审批",[[dataDic objectForKey:@"userList"] count]];
            }else if([GetHandleString(dataDic, @"type") intValue] == 2){
                header.timeLabel.text = [NSString stringWithFormat:@"%ld人会签审批",[[dataDic objectForKey:@"userList"] count]];
            }else if([GetHandleString(dataDic, @"type") intValue] == 3){
                header.timeLabel.text = [NSString stringWithFormat:@"%ld人或签审批",[[dataDic objectForKey:@"userList"] count]];
            }
        }
        
        return header;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section  > 4){
        return 59;
    }
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        ShenPiXiangQingBiaoTouTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiXiangQingBiaoTouTableViewCell"];
        cell.dataDictionary = dataInfoDictionary;
        return cell;
    }
    
    if(indexPath.section == 1){
        ShenPiXiangQingShenPiNeiRongTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiXiangQingShenPiNeiRongTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = keXuanXiangArray[indexPath.row];
        cell.model = model;
        return cell;
    }
    
    
    if(indexPath.section == 2){
        ShenPiXiangQingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiXiangQingTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataInfoDictionary;
        cell.model = model;
        return cell;
    }
    
    if(indexPath.section == 3){
        ShenPiXiangQingFuJianTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiXiangQingFuJianTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataInfoDictionary;
        cell.model = model;
        cell.manageClickBlock = ^(NSDictionary * _Nonnull resultDic, NSInteger manageType) {
            if(manageType == 101){
//                预览
                if([GetHandleString(resultDic, @"urlImage") containsString:@".mp3"]){
                    yuYinView.hidden = NO;
                    yuYinView.titleLabel.text = GetHandleString(resultDic, @"name");
                    yuYinView.voiceUrl = GetHandleString(resultDic, @"urlImage");
                }else{
                    LiaoTianWenJianChaKanViewController *yuLan = [[LiaoTianWenJianChaKanViewController alloc] init];
                    yuLan.loadUrl = GetHandleString(resultDic, @"urlImage");
                    [self pushViewController:yuLan];
                }
            }else{
//                下载
                [self downLoadWithFilePath:GetHandleString(resultDic, @"urlImage")];
            }
        };
        
        return cell;
    }
    
    if(indexPath.section == 4){
        ShenPiXiangQingGuanLianKeHuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiXiangQingGuanLianKeHuTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataInfoDictionary;
        cell.model = model;
        cell.userInfoClickBlock = ^(NSString * _Nonnull customerId) {
            KeHuXiangQingViewController *xiangQing = [[KeHuXiangQingViewController alloc] init];
            xiangQing.customerId = customerId;
            [self pushViewController:xiangQing];
        };
        return cell;
    }
    
    NSArray *userList = [examineFlowList[indexPath.section-5] objectForKey:@"userList"];
    
    ShenPiLiuChengRenYuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiLiuChengRenYuanTableViewCell"];
    AllModel *model = [[AllModel alloc] init];
    model.imageArray = liShiShenPiArray;
    model.modelInfoDictionary = userList[indexPath.row];
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        return 53;
    }
    
    if(indexPath.section == 1){
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = keXuanXiangArray[indexPath.row];
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ShenPiXiangQingShenPiNeiRongTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    
    if(indexPath.section == 2){
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataInfoDictionary;
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ShenPiXiangQingTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    
    if(indexPath.section == 3){
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataInfoDictionary;
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ShenPiXiangQingFuJianTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    
    if(indexPath.section == 4){
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataInfoDictionary;
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ShenPiXiangQingGuanLianKeHuTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    NSArray *userList = [examineFlowList[indexPath.section-5] objectForKey:@"userList"];
    AllModel *model = [[AllModel alloc] init];
    model.imageArray = liShiShenPiArray;
    model.modelInfoDictionary = userList[indexPath.row];
    return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ShenPiLiuChengRenYuanTableViewCell class] contentViewWidth:[self cellContentViewWith]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}


-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无需跟进客户"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无审批记录~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}


#pragma mark - 下载文件

- (void)downLoadWithFilePath:(NSString *)filePath {
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 11) {
        
    } else {
        [ZZPUtils showWarning:@"下载文件要求手机系统版本在11.0以上"];
        return;
    }
    [[ZZPRequest getWebUtil] addAnimation];
    [ZBRequestManager requestWithConfig:^(ZBURLRequest * request) {
         request.url =  filePath;
         request.methodType=ZBMethodTypeDownLoad;
         request.downloadState=ZBDownloadStateStart;//开始 //ZBDownloadStateStop暂停
     } progress:^(NSProgress * _Nullable progress) {
         NSLog(@"onProgress: %.2f", 100.f * progress.completedUnitCount/progress.totalUnitCount);
     } success:^(id  responseObject,ZBURLRequest * request) {
         
         
         [[ZZPRequest getWebUtil] hiddenAnimation];
         
         NSLog(@"ZBMethodTypeDownLoad 此时会返回存储路径文件: %@", responseObject);
          //在任何地方拿到下载文件
         NSString *file=[ZBRequestManager getDownloadFileForKey:request.url];
  
         NSLog(@"file:%@",file)
         
         UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath:file] inMode:UIDocumentPickerModeExportToService];
         // 设置代理
         documentPickerVC.delegate = self;
         // 设置模态弹出方式
         documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
         [self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
    
     } failure:^(NSError * _Nullable error) {
         NSLog(@"error: %@", error);
         [[ZZPRequest getWebUtil] hiddenAnimation];
     }];
}
 

 
#pragma mark - UIDocumentPickerDelegate
 
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // 获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            // 读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            //NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            if (error) {
                // 读取出错
            } else {
                // 上传
                NSLog(@"fileName : %@", fileName);
            }
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授权失败
    }
}



//拒绝
- (IBAction)juJue:(UIButton *)sender {
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];

    view.contentLabel.text = @"您确定要拒绝该审批吗？";

    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
        if(index == 102){
            [self juJueShenPi];
        }
        
    };
}

//拒绝审批
- (void)juJueShenPi{
    ShenPiJuJueView *view = [ShenPiJuJueView view];
    view.insertTxetView.placeholder = @"请输入原因描述";
    self.zh_popupController=[zhPopupController new];
    self.zh_popupController.slideStyle=zhPopupSlideStyleFade;
    self.zh_popupController.maskTouched = ^(zhPopupController * _Nonnull popupController) {
        [view endEditing:YES];
    };
    view.manageClickBlock = ^(NSInteger index) {
        [self.zh_popupController dismiss];
        
        if(index == 101){
            return;
        }
        
        if(view.insertTxetView.text.length == 0){
            [ZZPUtils showWarning:view.insertTxetView.placeholder];
            return;
        }
        
        NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
        [paraDic setValue:view.insertTxetView.text forKey:@"remarks"];
        [paraDic setValue:@"2" forKey:@"status"];
        [paraDic setValue:_recordId forKey:@"recordId"];
        [paraDic setValue:_examineId forKey:@"typeId"];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/examineRecord/auditExamine" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
            if(!error){
                [ZZPUtils showWarning:@"已拒绝"];
                
                if(_manageClickResultBlock){
                    _manageClickResultBlock();
                }
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }
        }];
        

    };
    [self.zh_popupController presentContentView:view];
}

//通过
- (IBAction)tongGuo:(UIButton *)sender {

    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"" forKey:@"remarks"];
    [paraDic setValue:@"1" forKey:@"status"];
    [paraDic setValue:_recordId forKey:@"recordId"];
    [paraDic setValue:_examineId forKey:@"typeId"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/examineRecord/auditExamine" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            [self shenPiChengGong];
        }
    }];
}
//审批成功
- (void)shenPiChengGong{
    AlertRemindView *view = [AlertRemindView view];
//    [ZZPUtils showAlertViewWithView:view andController:self];
    SPAlertController *alertController = [SPAlertController alertControllerWithCustomAlertView:view preferredStyle:SPAlertControllerStyleAlert animationType:SPAlertAnimationTypeDefault];
      alertController.minDistanceToEdges = 25;
      [self presentViewController:alertController animated:YES completion:nil];
    alertController.tapBackgroundViewDismiss = NO;
    view.leftButton.hidden = YES;
    view.rightButton.hidden = YES;
    view.centerButton.hidden = NO;
    view.topImage.image = LocalImagePath(@"公海领取弹窗成功");
    view.titleLabel.text = @"审批通过";
    view.contentLabel.text = @"恭喜审批通过！";
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
        NSLog(@"点击了：%ld",index);
        
        if(_manageClickResultBlock){
            _manageClickResultBlock();
        }
        
        [self.navigationController popViewControllerAnimated:YES];
        
    };
    

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


